import { Request, Response, RequestHandler } from 'express';
import { AIService, CreateDesignParams, DesignListParams, PublicDesignListParams, CreateTextToImageParams } from '../services/AIService';
import { AIProviderFactory, AIProviderType } from '../services/providers/AIProviderFactory';
import { asyncHandler } from '../utils/asyncHandler';
import { body, param, query, validationResult } from 'express-validator';
import { RoomType, DesignStyle } from '../entities/Design';

export class AIController {
  private aiService: AIService;

  constructor() {
    this.aiService = new AIService();
  }

  /**
   * 创建AI设计任务
   */
  createDesign: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    // 验证请求参数
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: errors.array()
      });
    }

    const { roomType, designStyle, customPrompt } = req.body;
    const userId = req.user?.id;
    const uploadedFile = req.file;

    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未认证'
      });
    }

    if (!uploadedFile) {
      return res.status(400).json({
        success: false,
        message: '请上传房间图片'
      });
    }

    try {
      const result = await this.aiService.createDesign({
        userId,
        roomType,
        designStyle,
        originalImageFile: uploadedFile,
        customPrompt
      });

      return res.status(201).json({
        success: true,
        data: result,
        message: 'AI设计任务创建成功，正在生成中...'
      });
    } catch (error: any) {
      return res.status(error.statusCode || 500).json({
        success: false,
        message: error.message || 'AI设计任务创建失败'
      });
    }
  });

  /**
   * 创建文生图设计任务
   */
  createTextToImageDesign: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    // 验证请求参数
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: errors.array()
      });
    }

    const { customPrompt } = req.body;
    const userId = req.user?.id;
    const uploadedFile = req.file;

    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未认证'
      });
    }

    if (!uploadedFile) {
      return res.status(400).json({
        success: false,
        message: '请上传房间图片'
      });
    }

    if (!customPrompt || customPrompt.trim() === '') {
      return res.status(400).json({
        success: false,
        message: '请输入设计提示词'
      });
    }

    try {
      const result = await this.aiService.createTextToImageDesign({
        userId,
        originalImageFile: uploadedFile,
        customPrompt: customPrompt.trim()
      });

      return res.status(201).json({
        success: true,
        message: '文生图设计任务创建成功',
        data: result
      });
    } catch (error: any) {
      return res.status(error.statusCode || 500).json({
        success: false,
        message: error.message || '创建文生图设计失败'
      });
    }
  });

  /**
   * 获取设计详情
   */
  getDesign: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { designId } = req.params;
    const userId = req.user?.id;

    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未认证'
      });
    }

    try {
      const design = await this.aiService.getDesign(designId, userId);

      return res.json({
        success: true,
        data: design,
        message: '获取设计详情成功'
      });
    } catch (error: any) {
      return res.status(error.statusCode || 500).json({
        success: false,
        message: error.message || '获取设计详情失败'
      });
    }
  });

  /**
   * 获取用户设计列表
   */
  getUserDesigns: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const userId = req.user?.id;

    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未认证'
      });
    }

    const { page, limit, status, roomType, designStyle } = req.query;

    try {
      const params: DesignListParams = {
        userId,
        page: page ? parseInt(page as string) : undefined,
        limit: limit ? parseInt(limit as string) : undefined,
        status: status as any,
        roomType: roomType as RoomType,
        designStyle: designStyle as DesignStyle
      };

      const result = await this.aiService.getUserDesigns(params);

      return res.json({
        success: true,
        data: result,
        message: '获取设计列表成功'
      });
    } catch (error: any) {
      return res.status(error.statusCode || 500).json({
        success: false,
        message: error.message || '获取设计列表失败'
      });
    }
  });

  /**
   * 获取公开设计列表（无需认证）
   */
  getPublicDesigns: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { page, limit, roomType, designStyle } = req.query;

    try {
      const params: PublicDesignListParams = {
        page: page ? parseInt(page as string) : undefined,
        limit: limit ? parseInt(limit as string) : undefined,
        roomType: roomType as RoomType,
        designStyle: designStyle as DesignStyle
      };

      const result = await this.aiService.getPublicDesigns(params);

      return res.json({
        success: true,
        data: result,
        message: '获取公开设计列表成功'
      });
    } catch (error: any) {
      return res.status(error.statusCode || 500).json({
        success: false,
        message: error.message || '获取公开设计列表失败'
      });
    }
  });

  /**
   * 更新设计公开状态
   */
  updateDesignPublicStatus: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { designId } = req.params;
    const { isPublic } = req.body;
    const userId = req.user?.id;

    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未认证'
      });
    }

    // 验证请求参数
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数验证失败',
        errors: errors.array()
      });
    }

    try {
      const updatedDesign = await this.aiService.updateDesignPublicStatus(designId, userId, isPublic);

      return res.json({
        success: true,
        data: updatedDesign,
        message: '设计公开状态更新成功'
      });
    } catch (error: any) {
      return res.status(error.statusCode || 500).json({
        success: false,
        message: error.message || '更新设计公开状态失败'
      });
    }
  });

  /**
   * 删除设计记录
   */
  deleteDesign: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { designId } = req.params;
    const userId = req.user?.id;

    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未认证'
      });
    }

    try {
      await this.aiService.deleteDesign(designId, userId);

      return res.json({
        success: true,
        message: '设计记录删除成功'
      });
    } catch (error: any) {
      return res.status(error.statusCode || 500).json({
        success: false,
        message: error.message || '删除设计记录失败'
      });
    }
  });

  /**
   * 获取设计统计信息
   */
  getDesignStats: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const userId = req.user?.id;

    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未认证'
      });
    }

    try {
      const stats = await this.aiService.getDesignStats(userId);

      return res.json({
        success: true,
        data: stats,
        message: '获取设计统计成功'
      });
    } catch (error: any) {
      return res.status(error.statusCode || 500).json({
        success: false,
        message: error.message || '获取设计统计失败'
      });
    }
  });

  /**
   * 获取支持的房间类型
   */
  getRoomTypes: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const roomTypes = [
      { value: 'living', label: '客厅', description: '舒适的起居空间' },
      { value: 'bedroom', label: '卧室', description: '宁静的休息空间' },
      { value: 'kitchen', label: '厨房', description: '功能性烹饪空间' },
      { value: 'bathroom', label: '浴室', description: '私密的洗浴空间' },
      { value: 'office', label: '办公室', description: '高效的工作空间' },
      { value: 'dining', label: '餐厅', description: '优雅的用餐空间' }
    ];

    return res.json({
      success: true,
      data: roomTypes,
      message: '获取房间类型成功'
    });
  });

  /**
   * 获取支持的设计风格
   */
  getDesignStyles: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const designStyles = [
      { value: 'modern', label: '现代风格', description: '简洁线条，极简家具，中性色彩' },
      { value: 'traditional', label: '传统风格', description: '经典家具，温暖色彩，丰富质感' },
      { value: 'scandinavian', label: '北欧风格', description: '浅色木材，白色基调，舒适纺织品' },
      { value: 'industrial', label: '工业风格', description: '裸露砖墙，金属装置，深色调' },
      { value: 'bohemian', label: '波西米亚风格', description: '折衷图案，鲜艳色彩，天然材料' },
      { value: 'minimalist', label: '极简风格', description: '简单形式，单色调，整洁空间' }
    ];

    return res.json({
      success: true,
      data: designStyles,
      message: '获取设计风格成功'
    });
  });

  /**
   * 获取AI提供商状态
   */
  getAIProviderStatus: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const status = AIProviderFactory.getProviderStatus();
    const currentProvider = AIProviderFactory.getCurrentProviderType();
    const availableProviders = AIProviderFactory.getAvailableProviders();

    return res.json({
      success: true,
      data: {
        currentProvider,
        availableProviders,
        providerStatus: status
      },
      message: '获取AI提供商状态成功'
    });
  });

  /**
   * 切换AI提供商
   */
  switchAIProvider: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { provider } = req.body;

    if (!provider || !['openai', 'wanx'].includes(provider)) {
      return res.status(400).json({
        success: false,
        message: '无效的AI提供商类型，支持的类型：openai, wanx'
      });
    }

    const success = AIProviderFactory.switchProvider(provider as AIProviderType);
    
    if (success) {
      return res.json({
        success: true,
        data: {
          currentProvider: AIProviderFactory.getCurrentProviderType(),
          availableProviders: AIProviderFactory.getAvailableProviders()
        },
        message: `成功切换到 ${provider} 提供商`
      });
    } else {
      return res.status(400).json({
        success: false,
        message: `无法切换到 ${provider} 提供商，该提供商不可用`
      });
    }
  });
}

// 验证中间件
export const createDesignValidation = [
  body('roomType')
    .isIn(['living-room', 'living', 'bedroom', 'kitchen', 'bathroom', 'office', 'dining-room', 'dining', 'game-room', 'basement', 'outdoor-terrace'])
    .withMessage('房间类型无效'),
  body('designStyle')
    .isIn(['modern', 'traditional', 'minimalist', 'scandinavian', 'industrial', 'bohemian', 'tribal', 'cyberpunk', 'coastal', 'professional'])
    .withMessage('设计风格无效'),
  body('customPrompt')
    .optional()
    .isLength({ max: 1000 })
    .withMessage('自定义提示词不能超过1000个字符')
];

export const designIdValidation = [
  param('designId')
    .isUUID()
    .withMessage('设计ID格式无效')
];

export const updateDesignPublicStatusValidation = [
  param('designId')
    .isUUID()
    .withMessage('设计ID格式无效'),
  body('isPublic')
    .isBoolean()
    .withMessage('isPublic必须是布尔值')
];

export const createTextToImageValidation = [
  body('customPrompt')
    .notEmpty()
    .withMessage('设计提示词不能为空')
    .isLength({ max: 1000 })
    .withMessage('设计提示词长度不能超过1000个字符')
];